import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.net.UnknownHostException;


public class Tuner extends Thread {
	private int port=0;
	InetAddress address;
	MulticastSocket socket;
	
	public Tuner(int port){
		this.port=port;
		
		try{			
			socket=new MulticastSocket(this.port);
			address = InetAddress.getByName("230.0.0.1");
			socket.joinGroup(address);			
		}catch(UnknownHostException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
		
	}
	
	public void run(){		
		System.out.println("Tuner listens at port " + this.port);
		while(true){
			tune();
			try{				
				Thread.sleep(100);
			}catch(InterruptedException e){
				e.printStackTrace();					
			}
			
		}
		
	}
	
	public void tune(){
		byte[] buf = new byte[256*8];
		DatagramPacket packet = new DatagramPacket(buf, buf.length);
		
		try{						
			socket.receive(packet);
			
			//deserialize byte[] into User
			byte[] byteUser=packet.getData();			
			ByteArrayInputStream bais=new ByteArrayInputStream(byteUser);
			java.io.ObjectInputStream ois=new ObjectInputStream(bais);
			Object o=ois.readObject();
			
			if(o instanceof User){
				User u=(User)o;				
				NetworkManager.getInstance().addUser(u);
			}		
			
			
		}catch(IOException e){ //socket.receive and new ObjectInputStream throws this exception
			System.out.println("Error in tuning...");
			e.printStackTrace();
			socket.close();
		}catch(ClassNotFoundException ce){ //ois.readObject throws this exception
			System.out.println("Error in typecasting Message");
			ce.printStackTrace();
			socket.close();
		}
	}
}
